#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import requests, hashlib, base64, time, json, datetime, pymysql
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
from random import Random
from Crypto.Cipher import AES
from django.conf import settings

from cashbonus.models import *


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


def get_sign(data_dict, secret):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&secret=' + secret
    md5 = hashlib.md5()
    md5.update(params_str.encode('utf-8'))
    sign = md5.hexdigest().upper()
    return sign


def pkcs7_padding(data):
    if not isinstance(data, bytes):
        data = data.encode()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(data) + padder.finalize()
    return padded_data


def encrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def decrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    text = base64.b64decode(text.encode('utf8'))
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    plain_text = cryptor.decrypt(text)
    return bytes.decode(plain_text).rstrip('\0').rstrip("\x01").rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05").rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09").rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d").rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


def post_result(method, body):
    appid = 'imapQPtHDERnbiYSrACi'
    key = 'x17jweJfs2peeGUsTdcRR6pNgZmARMIm'
    iv = 'scQG8UlQ3RGkCk4q'
    secret = '9s2LV99FGzoUjR0eRYii2scGX46WcE8l'
    # token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Nzc4NzI4MjMsImlhdCI6MTY3NzgyOTYyMywidXNlcklkIjoiMjM4NDAzMTYyODQxNzUxNzA4In0.-IsscKZvjqHSdRLoCF2QfhBgvQLHP9HQDiEg2DUu8gg'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    data_dict['appId'] = appid
    signture = get_sign(data_dict, secret)
    headers = {
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'sign-app-id': appid,
        'content-type': 'application/json'
    }
    url = 'https://equity.wxmas.com/equitygateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def push_withdrawal():
    print('%s: push_withdrawal' % time.ctime())
    conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                           port=settings.DATABASES['default']['PORT'],
                           database=settings.DATABASES['default']['NAME'],
                           user=settings.DATABASES['default']['USER'],
                           password=settings.DATABASES['default']['PASSWORD'])
    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
    sql = f'''SELECT g.*,h.account_nine FROM (SELECT e.*,f.nickname,manager_mobile,level_id FROM (SELECT c.*,d.realname,idcode,mobile,new_openid,ali_user_id FROM (SELECT a.*,b.activity_id,activity_name FROM (SELECT id,companyuser_id,cash_activity_id,customer_user_id,amount,DATE_FORMAT(create_time,'%Y-%m-%d')AS create_time,DATE_FORMAT(received_time,'%Y-%m-%d %H:%i:%S')AS received_time,payment_no,channel_id FROM tb_cash_activity_data WHERE is_push_ylx IS NULL AND state=2 AND cash_activity_id IN (SELECT id FROM tb_cash_activity WHERE is_push_ylx=1))AS a LEFT JOIN (SELECT id,name AS activity_name,activity_id FROM tb_cash_activity WHERE is_push_ylx=1)AS b ON a.cash_activity_id=b.id)AS c LEFT JOIN (SELECT id,realname,idcode,mobile,new_openid,ali_user_id FROM tb_u_customer_user)AS d ON c.customer_user_id=d.id)AS e LEFT JOIN (SELECT id,nickname,mobile AS manager_mobile,level_id FROM tb_u_user)AS f ON e.companyuser_id=f.id)AS g LEFT JOIN (SELECT id,account_nine FROM tb_u_level)AS h ON g.level_id=h.id;'''
    cursor.execute(sql)
    rows = cursor.fetchall()
    cursor.close()
    conn.close()
    method = 'FeedAllWbCustAct'
    if rows:
        cash_id_list = []
        feedAllWbCustActList = []
        for row in rows:
            cash_id_list.append(row['id'])
            if len(feedAllWbCustActList) >= 100:
                body = {
                    "remarks": datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                    "feedAllWbCustActList": feedAllWbCustActList
                }
                print("--------------请求参数-------------")
                print(body)
                print("--------------响应参数-------------")
                result = post_result(method, body)
                print(result)
                feedAllWbCustActList = []
            data = {}
            data['custActId'] = str(row['id'])
            data['cstmName'] = row['realname']
            data['idCode'] = row['idcode']
            data['phone'] = row['mobile']
            data['orgId'] = row['account_nine']
            data['useDate'] = row['create_time']
            data['handOutDate'] = row['received_time']
            data['wbActId'] = row['activity_id']
            data['wbActName'] = row['activity_name']
            data['giftMoney'] = float(row['amount'])
            data['status'] = 1
            data['openId'] = row['new_openid'] if row['channel_id'] == 9 else row['ali_user_id']
            data['handOutName'] = row['nickname']
            data['handOutPhone'] = row['manager_mobile']
            data['handOutOrgId'] = row['account_nine']
            data['handOutId'] = row['payment_no']
            data['handOutBelongOrgId'] = row['account_nine']
            data['channelId'] = 6
            data['actWay'] = '3'
            feedAllWbCustActList.append(data)
        if feedAllWbCustActList:
            body = {
                "remarks": datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                "feedAllWbCustActList": feedAllWbCustActList
            }
            print("--------------请求参数-------------")
            print(body)
            print("--------------响应参数-------------")
            print(post_result(method, body))
        CashActivityData.objects.filter(id__in=cash_id_list).update(is_push_ylx=1)


if __name__ == '__main__':
    push_withdrawal()